from hosting.ftp.models import FTPUser
from django.contrib.auth.decorators import login_required
from django.views.generic import list_detail, simple
from hosting.ftp.forms import FTPForm, FTPFormWOPass
from django.shortcuts import render_to_response
from hosting.system.user import generate_password
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

# Create your views here.
def _edit_form(self):
    return FTPForm(auto_id=False, instance=self)

FTPUser.edit_form = property(_edit_form)


@login_required
def list_ftpuser(request):
    ftpusers = FTPUser.objects.filter(user=request.user),
    extra_context = {'forms': [FTPForm(request=request, instance=ftpuser) for ftpuser in ftpusers[0]]}
    return list_detail.object_list(
        request,
        queryset = FTPUser.objects.filter(user=request.user),
        extra_context = extra_context,
    )

@login_required
def ftpuser_detail(request, ftpuser_id):
    ftpuser = FTPUser.objects.get(user=request.user, pk=ftpuser_id)
    form = FTPFormWOPass(request=request, instance=ftpuser)
    return simple.direct_to_template(request, 'ftp/ftpuser.html', {'form': form})

@login_required
def ftpuser_add(request):
    user = request.user
    if request.method == 'POST':
        form = FTPForm(request.POST)
        if form.is_valid():
            form.save()
    return HttpResponseRedirect(reverse(list_ftpuser))

@login_required
def change_password(request, ftpuser_id):
    user = request.user
    ftpuser = FTPUser.objects.get(user=user,pk=ftpuser_id)
    ftpuser.password = generate_password()
    ftpuser.save()
    return HttpResponseRedirect(reverse(list_ftpuser))

